package com.jasper.dagger2learn.utils

import android.text.TextUtils
import android.widget.Toast
import androidx.annotation.StringRes
import com.jasper.dagger2learn.APP

//object 相当于单例
object ToastUtil {
    val TAG = "ToastUtil"
    var toast: Toast? = null
    private var oldMsg: String? = null
    private var oneTime: Long = 0
    private var twoTime: Long = 0

    private fun showToast(s: String, duration: Int) {
        //LENGTH_SHORT:2000, LENGTH_LONG:3500
        val dur = if (duration == Toast.LENGTH_SHORT) 2000 else 3500
        if (toast == null) {
            toast = Toast.makeText(APP.context, s, duration)
            toast?.show()
            oneTime = System.currentTimeMillis()
//            LogUtil.d(TAG, "toast == null")
        } else {
            twoTime = System.currentTimeMillis()
            if (s == oldMsg) {
//                LogUtil.d(TAG, "s == oldMsg, twoTime - oneTime = " + (twoTime - oneTime))
                if (twoTime - oneTime > dur) {
//                    LogUtil.d(TAG, "s == oldMsg, show")
                    toast?.show()
                    oneTime = twoTime
                }
            } else {
                if (twoTime - oneTime < dur) {
                    toast?.cancel()
                }
                oldMsg = s
                toast?.setText(s)
//                LogUtil.d(TAG, "s != oldMsg, show")
                toast?.show()
                oneTime = twoTime
            }
        }

    }

    fun showShort(msg: String) {
        if (TextUtils.isEmpty(msg)) {
            toast?.cancel()
            return
        }
        showToast(msg, Toast.LENGTH_SHORT)
    }

    fun showShort(@StringRes id: Int) {
        showToast(APP.context.getString(id), Toast.LENGTH_SHORT)
    }

    fun showLong(msg: String) {
        if (TextUtils.isEmpty(msg)) {
            toast?.cancel()
            return
        }
        showToast(msg, Toast.LENGTH_LONG)
    }

    fun showLong(@StringRes id: Int) {
        showToast(APP.context.getString(id), Toast.LENGTH_LONG)
    }
}